package com.weetop.akly.activity.work;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qmuiteam.qmui.layout.QMUIButton;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.weetop.akly.R;
import com.weetop.akly.activity.communicationIndex.IndexActivity;
import com.weetop.akly.adapter.FullyGridLayoutManager;
import com.weetop.akly.adapter.MyGridImageAdapter;
import com.weetop.akly.adapter.MyGridSpryAdapter;
import com.weetop.akly.base.BaseActivity;
import com.weetop.akly.base.mvp.BaseModel;
import com.weetop.akly.bean.AccountInfoBean;
import com.weetop.akly.bean.ApproveFromKeyBean;
import com.weetop.akly.bean.MemberBean;
import com.weetop.akly.presenter.WorkApplyPresent;
import com.weetop.akly.utils.BaseUtils;
import com.weetop.akly.utils.MyDataCleanManager;
import com.weetop.akly.utils.widget.AlertDialogIOS;
import com.weetop.akly.view.WorkApplyView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OutApplyActivity extends BaseActivity<WorkApplyPresent> implements WorkApplyView {

    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.tv_data_title)
    TextView tvDataTitle;
    @BindView(R.id.tv_qjry)
    TextView tvQjry;
    @BindView(R.id.tv_ssbm)
    TextView tvSsbm;
    @BindView(R.id.tv_ssgw)
    TextView tvSsgw;
    @BindView(R.id.tv_rybh)
    TextView tvRybh;
    @BindView(R.id.tv_starttime)
    TextView tvStarttime;
    @BindView(R.id.rl_starttime)
    RelativeLayout rlStarttime;
    @BindView(R.id.tv_endtime)
    TextView tvEndtime;
    @BindView(R.id.rl_endtime)
    RelativeLayout rlEndtime;
    @BindView(R.id.et_daycount)
    EditText etDaycount;
    @BindView(R.id.et_reason)
    EditText etReason;
    @BindView(R.id.rv_fujian)
    RecyclerView rvFujian;
    @BindView(R.id.rv_shenpirenyuan)
    RecyclerView rvShenpirenyuan;
    @BindView(R.id.bt_submit)
    QMUIButton btSubmit;
    @BindView(R.id.tv_sfhgs)
    TextView tvSfhgs;
    @BindView(R.id.rl_sfhgs)
    RelativeLayout rlSfhgs;

    private List<LocalMedia> selectList = new ArrayList<>();
    private ArrayList<MemberBean> selectSpryList = new ArrayList<>();

    private MyGridImageAdapter adapter;
    private MyGridSpryAdapter spAdapter;
    private AccountInfoBean.InfoBean info;
    private AccountInfoBean.AccountBean accountInfo;
    private TimePickerView pvTime;
    private QMUIBottomSheet chooseGroupSheet;
    private String startTime, endTime;
    private ArrayList<ApproveFromKeyBean> approveKeys;
    private String modelId = "3";
    private int sfhgs = 1;
    private String reason;
    private String dayCount;
    private AlertDialogIOS myDialog;
    ;

    @Override
    protected WorkApplyPresent createPresenter() {
        return new WorkApplyPresent(this, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_out_apply);
        ButterKnife.bind(this);

        setTitleInfo("外出申请");
        mPresenter.getApproveFormKeyList(modelId);
        initSfhgs();
        initTimePicker();
        initUserInfo();
        initFuJianRv();
        initShenpirenRv();
    }

    private void initSfhgs() {
        String sfhgs = this.sfhgs == 1 ? "回" : "不回";
        tvSfhgs.setText(sfhgs);
        myDialog = new AlertDialogIOS(this).builder();
    }

    private void initFuJianRv() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mActivity, 4, GridLayoutManager.VERTICAL, false);
        rvFujian.setLayoutManager(manager);
//        adapter = new MyGridImageAdapter(mActivity, onAddPicClickListener);
        adapter = new MyGridImageAdapter(mActivity, onAddPicClickListener, true);
        adapter.setList(selectList);
        adapter.setSelectMax(4);
        rvFujian.setAdapter(adapter);
    }

    private void initShenpirenRv() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mActivity, 1, GridLayoutManager.HORIZONTAL, false);
        rvShenpirenyuan.setLayoutManager(manager);
        spAdapter = new MyGridSpryAdapter(mActivity, onAddSpryClickListener, true);
        spAdapter.setList(selectSpryList);
        rvShenpirenyuan.setAdapter(spAdapter);
    }

    private void initUserInfo() {
        AccountInfoBean accountInfoBean = myApplication.getAccountInfoBean();
        info = accountInfoBean.getInfo();
        accountInfo = accountInfoBean.getAccount();
        tvQjry.setText(info.getName());
        tvSsbm.setText(info.getDepartment());
        tvSsgw.setText(info.getJob());
        tvRybh.setText(accountInfo.getAccount());
    }

    private MyGridImageAdapter.onAddPicClickListener onAddPicClickListener = new MyGridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(mActivity)
                    .openGallery(PictureMimeType.ofImage())
                    .maxSelectNum(4 - selectList.size())
                    .compress(true)// 是否压缩 true or false
                    .enableCrop(false)
                    .minimumCompressSize(350)// 小于100kb的图片不压缩
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    };

    private MyGridSpryAdapter.onAddSpryClickListener onAddSpryClickListener = new MyGridSpryAdapter.onAddSpryClickListener() {
        @Override
        public void onAddSpryClick() {
            Intent intent = new Intent();
            intent.putExtra("mode_id", modelId);
            BaseUtils.toActivity(mActivity, IndexActivity.class, intent);
        }
    };

    private void initTimePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String chooseTime = getTime(date);
                switch (v.getId()) {
                    case R.id.rl_starttime:
                        startTime = chooseTime + ":00";
                        tvStarttime.setText(startTime);
                        break;
                    case R.id.rl_endtime:
                        endTime = chooseTime + ":00";
                        tvEndtime.setText(endTime);
                        break;
                }
                Log.i("pvTime", "onTimeSelect");

            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");
                    }
                })
                .setType(new boolean[]{true, true, true, true, true, false})
                .setLabel("年", "月", "日", "时", "分", "")
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        String pattern = "yyyy-MM-dd HH:mm";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> datapic = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(datapic);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    public void getApproveFormKeySuccess(BaseModel<ArrayList<ApproveFromKeyBean>> o) {
        approveKeys = o.getData();
    }


    @Override
    public void submitSuccess(BaseModel<Object> o) {
        ToastUtils.showShort("提交成功");
        finish();
    }

    @Override
    public void uploadSucess(String filePaths) {
        String leaderIds = "";
        for (MemberBean leader : selectSpryList) {
            if (TextUtils.isEmpty(leaderIds)) {
                leaderIds = leader.getId() + "";
            } else {
                leaderIds = leaderIds + "," + leader.getId() + "";
            }
        }
        HashMap<String, String> form = new HashMap<>();
        for (int i = 0; i < approveKeys.size(); i++) {
            ApproveFromKeyBean formKey = approveKeys.get(i);
            form.put("form[" + i + "][form_id]", formKey.getForm_id() + "");
            if ("外出原因".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", reason);
            } else if ("是否回公司".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", sfhgs + "");
            } else if ("开始时间".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", startTime);
            } else if ("结束时间".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", endTime);
            } else if ("合计时长".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", dayCount);
            }
        }
        form.clear();
        form.put("start_time", startTime);
        form.put("end_time", endTime);
        form.put("count_day", dayCount);
        form.put("leave_reason", reason);
        form.put("approve_user_id", leaderIds);
        mPresenter.goOutAdd(form);
    }


    @OnClick({R.id.rl_starttime, R.id.rl_endtime, R.id.bt_submit, R.id.rl_sfhgs})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_starttime:
            case R.id.rl_endtime:
                pvTime.show(view);
                break;
            case R.id.bt_submit:
                reason = etReason.getText().toString().trim();
                dayCount = etDaycount.getText().toString().trim();
                if (TextUtils.isEmpty(startTime)) {
                    ToastUtils.showShort("请选择开始时间");
                    return;
                } else if (TextUtils.isEmpty(endTime)) {
                    ToastUtils.showShort("请选择结束时间");
                    return;
                } else if (TextUtils.isEmpty(reason)) {
                    ToastUtils.showShort("请填写原因");
                    return;
                } else if (TextUtils.isEmpty(dayCount)) {
                    ToastUtils.showShort("请填写外出时长");
                    return;
                } else if (selectSpryList.size() <= 0) {
                    ToastUtils.showShort("请添加审批人员");
                    return;
                }
//                mPresenter.uploadFiles(selectList);
                String leaderIds = "";
                for (MemberBean leader : selectSpryList) {
                    if (TextUtils.isEmpty(leaderIds)) {
                        leaderIds = leader.getId() + "";
                    } else {
                        leaderIds = leaderIds + "," + leader.getId() + "";
                    }
                }
                HashMap<String, String> form = new HashMap<>();
                for (int i = 0; i < approveKeys.size(); i++) {
                    ApproveFromKeyBean formKey = approveKeys.get(i);
                    form.put("form[" + i + "][form_id]", formKey.getForm_id() + "");
                    if ("外出原因".equals(formKey.getForm_key())) {
                        form.put("form[" + i + "][form_val]", reason);
                    } else if ("是否回公司".equals(formKey.getForm_key())) {
                        form.put("form[" + i + "][form_val]", sfhgs + "");
                    } else if ("开始时间".equals(formKey.getForm_key())) {
                        form.put("form[" + i + "][form_val]", startTime);
                    } else if ("结束时间".equals(formKey.getForm_key())) {
                        form.put("form[" + i + "][form_val]", endTime);
                    } else if ("合计时长".equals(formKey.getForm_key())) {
                        form.put("form[" + i + "][form_val]", dayCount);
                    }
                }
                form.clear();
                form.put("start_time", startTime);
                form.put("end_time", endTime);
                form.put("count_day", dayCount);
                form.put("leave_reason", reason);
                form.put("approve_user_id", leaderIds);
                mPresenter.goOutAdd(form);
                break;
            case R.id.rl_sfhgs:
                myDialog.setGone().setTitle(" ").setMsg("是否回公司？").setNegativeButton("否", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sfhgs = 0;
                        tvSfhgs.setText("不回");
                    }
                }).setPositiveButton("是", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sfhgs = 1;
                        tvSfhgs.setText("回");
                    }
                }).show();
                break;
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String select_members = intent.getStringExtra("select_members");
        if (!TextUtils.isEmpty(select_members)) {
            ArrayList<MemberBean> selectMembers = GsonUtils.fromJson(select_members, GsonUtils.getListType(MemberBean.class));
            selectSpryList.addAll(selectMembers);
            spAdapter.setList(selectSpryList);
            spAdapter.notifyDataSetChanged();
        }
    }
}
